var express = require('express');
var router = express.Router();
var sql = require('../sql');
var Pro = require('../sql/col/Pro');

router.get('/', function(req,res, next) {
    res.send('search相关接口')
});

/**
 * @api {get} /api/search/getCategory 获取分类信息
 * @apiName GetCategory
 * @apiGroup search
 * @apiSuccessExample {json} Success-Response:
 *  res.send({
        code: '200',
        message: '获取分类信息成功',
        data
    })
 * @apiSampleRequest /api/search/getCategory
 * @apiVersion 0.0.0
 */
router.get('/getCategory', (req, res, next) => {
    sql.distinct(Pro, 'category').then(data => {
        res.send({
            code: '200',
            message: '获取商品分类信息成功',
            data
        })
    })
})


/**
 * @api {get} /api/search/getCategoryLogo 获取商品分类下品牌等信息
 * @apiName GetCategoryLogo
 * @apiGroup search
 * 
*  @apiParam { string } category 商品分类
 * @apiSuccessExample {json} Success-Response:
 *  res.send({
        code: '200',
        message: '获取该分类下品牌等信息成功',
        data
    })
 * @apiSampleRequest /api/search/getCategoryLogo
 * @apiVersion 0.0.0
 */
router.get('/getCategoryLogo', (req, res, next) => {
    const { category } = req.query
    sql.find(Pro,{ category }, { _id: 0, brand: 1, logo: 1}).then(data => {
        const obj = {}
        const arr = data.reduce((item, next) => {
            obj[next.brand] ? '' : obj[next.brand] = true && item.push(next)
            return item 
        }, [])
        res.send({
            code: '200',
            message: '获取该商品分类下品牌等信息成功',
            data: arr
        })
    })
})

/**
 * @api {get} /api/search/getCategoryBrandList 获取商品的分类下的品牌的列表数据
 * @apiName GetCategoryList
 * @apiGroup search
 * @apiParam { string } category
 * @apiParam { string } brand
 * @apiSuccessExample {json} Success-Response:
 *  res.send({
      code: '200',
      message: '获取商品的分类下的品牌的列表数据',
      data
    })

 * @apiSampleRequest /api/search/getCategoryBrandList
 * @apiVersion 0.0.0
 */
router.get('/getCategoryBrandList', (req, res, next) => {
    const { category, brand } = req.query
    sql.find(Pro, { category, brand }, { _id: 0 }).then(data => {
      res.send({
        code: '200',
        message: '获取商品的分类下的品牌的列表数据',
        data
      })
    })
})

/**
 * @api {get} /api/search/fuzzySearch 商品的模糊查询
 * @apiName GetCategoryList
 * @apiGroup search
 * @apiParam { string } category
 * @apiParam { string } brand
 * @apiSuccessExample {json} Success-Response:
 * res.send({
     code:'200',
     message:'搜索查询',
     data
    })
 * @apiSampleRequest /api/search/fuzzySearch
 * @apiVersion 0.0.0
 */
router.post('/fuzzySearch',(req,res,next)=>{
    // 通过查询想的 商品的名称,品牌 分类来获取数据
    const { keywords } = req.body
    const reg = new RegExp(keywords.replace(/([.?*+^$[\]\\(){}|-])/ig, "\\$1"), 'ig')//正则解析变量
    sql.find(Pro,{ $or:[{category: reg},{brand: reg},{ proname:reg }]}).then(data=>{
        res.send({
            code:'200',
            message:'模糊搜索查询',
            data
        })
    })
})

module.exports = router;